package com.baohua.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baohua.exception.BaohuaSystemException;
import com.baohua.model.Inventory;
import com.baohua.model.Staff;
import com.baohua.service.InventoryService;

@Controller
@RequestMapping("/inventory")
public class InventoryController {
 
	/**
	 * 跳转到库存主页面
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return "inventory";
	}
	
	/**
	 * 根据条件查询库存列表
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/list")
	public @ResponseBody Map queryList(Inventory inventory, HttpServletRequest request){
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		//获取前置总额
		String pre_priceAmount = request.getParameter("pre_priceAmount");
		//获取后置总额
		String af_priceAmount = request.getParameter("af_priceAmount");
		//获取前置当前库存
		String pre_inventoryAmount = request.getParameter("pre_inventoryAmount");
		//获取后置当前库存
		String af_inventoryAmount = request.getParameter("af_inventoryAmount");
		
		Map map = inventoryService.getInventoryList(inventory, pre_priceAmount, af_priceAmount, af_inventoryAmount, pre_inventoryAmount, page, pageSize);
		
		return map;
	}
	
	/**
	 * 增加新的物料信息
	 * @param inventory
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String addInventory(Inventory inventory, Model model) {
		 try{
	    	 inventoryService.addRawMaterial(inventory);
		  } catch (BaohuaSystemException e) {
		 		logger.info(e.getMessage());
		 		model.addAttribute("errorMessage", e.getMessage());
		 		return "forward:/system/error";
		  } 
		return "redirect:/inventory/index";
	}
	
	/**
	 * 修改物料信息, 不允许修改当前库存
	 * @param i
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String updateInventory(Inventory i, Model model) {
     try{
    	 inventoryService.updateInventory(i);
	  } catch (BaohuaSystemException e) {
	 		logger.info(e.getMessage());
	 		model.addAttribute("errorMessage", e.getMessage());
	 		return "forward:/system/error";
	  } 
	return "redirect:/inventory/index";
	}
	
	/**
	 * 只用库存为0时 , 才可以删除
	 * @param rowsNum
	 * @return
	 */
	@RequestMapping(value="/del/{rowsNum}", method=RequestMethod.GET)
	public @ResponseBody String delInventory(@PathVariable String rowsNum) {
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			String[] mIds = objectMapper.readValue(rowsNum, String[].class);
			for(String mId : mIds) {
				inventoryService.delRawMaterial(Integer.parseInt(mId));
			}
		} catch (JsonParseException e) {
			logger.info(e.getMessage());
			return "{message:systemerror}";
		} catch (JsonMappingException e) {
			logger.info(e.getMessage());
			return "{message:'systemerror'}";
		}  catch (BaohuaSystemException e) {
			logger.info(e.getMessage());
			return "{message:'error'}";
		} catch (IOException e) {
			logger.info(e.getMessage());
			return "{message:'systemerror'}";
		}
		return "{message : 'success'}";
	}
	
	@RequestMapping("export")
	public String export(HttpServletRequest request, HttpServletResponse response) {
		List<Inventory> list = new ArrayList<Inventory>(); 
		String param = request.getParameter("param");
		try {
			if(!StringUtils.isBlank(param)) {
			  String[] inventoryNOs = param.split(",");
			 list = inventoryService.queryByInventoryNOs(inventoryNOs);
			}
			
			Date date = new Date();
			inventoryService.exportData("库存列表" + date.getTime() + ".xls", 
					list, "库存列表", request, response);
		} catch (IllegalArgumentException e) {
			logger.info(e.getMessage());
		} catch (IOException e) {
			logger.info(e.getMessage());
		} catch (IllegalAccessException e) {
			logger.info(e.getMessage());
		}
		return null;
	}
	
	
	private InventoryService inventoryService;
	private static final Logger logger = Logger.getLogger(InventoryController.class.getName());
	
	public InventoryService getInventoryService() {
		return inventoryService;
	}

	@Resource(name="inventoryService")
	public void setInventoryService(InventoryService inventoryService) {
		this.inventoryService = inventoryService;
	}

	
}
